package cn.wecloud.im.multiplayervideodemo.act

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import cn.wecloud.im.multiplayervideodemo.App
import cn.wecloud.im.multiplayervideodemo.R
import cn.wecloud.im.multiplayervideodemo.http.HttpException
import cn.wecloud.im.multiplayervideodemo.http.HttpManager
import cn.wecloud.im.multiplayervideodemo.http.SchedulerUtils
import cn.wecloud.im.multiplayervideodemo.http.errorConsumer
import cn.wecloud.im.multiplayervideodemo.live.MultiVideoArgs
import cn.wecloud.im.multiplayervideodemo.utils.AppSharePre
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = AppSharePre.getClientId()

        btnInvitation.setOnClickListener {
            val clientids =  etClientIds.text.toString().trim().split(",")
            if (clientids.isEmpty()) {
                Toast.makeText(this, "请输入ClientId", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            openVideo(clientids)
        }
    }


    private fun openVideo(clientids: List<String>) {
        val timestamp = System.currentTimeMillis().toString()
        val clientId = AppSharePre.getClientId()
        val appKey = App.APP_KEY
        val platform = 2
        val appSecret = App.APP_SECRET
        //最多20人 ,获取sing,创建房间,发出邀请
        val d = HttpManager().getMultiMeetSign(timestamp, clientId, appKey, platform, appSecret)
            .flatMap {
                val sing = it.data
                if (TextUtils.isEmpty(sing))
                    throw HttpException(-1, "sing获取失败")
                HttpManager().createMeetLive(clientId, appKey, sing!!, platform, timestamp)
            }
            .compose(SchedulerUtils.ioToMain())
            .subscribe({
                val roomId = it.data?.roomId ?: return@subscribe
                val token = it.data?.token ?: return@subscribe
                val inviteeUsers = arrayListOf<String>()
                    .apply { addAll(clientids) }
                val args = MultiVideoArgs.generateCallingArgs(
                    0L,
                    roomId,
                    token,
                    AppSharePre.getClientId(),
                    inviteeUsers
                )
                val intent = MultipleVideoActivity.getIntent(this, args )
                startActivity(intent)
            }, errorConsumer { msg ->
                Toast.makeText(this,msg,Toast.LENGTH_SHORT).show()
            })
    }
}